package com.zzyl.service.impl;

import com.zzyl.constant.Constants;
import com.zzyl.dto.CustomerUserLoginDto;
import com.zzyl.entity.Member;
import com.zzyl.properties.JwtProperties;
import com.zzyl.service.CustomerLoginService;
import com.zzyl.service.MemberService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class CustomerLoginServiceImpl implements CustomerLoginService {

    @Autowired
    private MemberService memberService;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private JwtProperties jwtProp;

    @Override
    public LoginVo login(CustomerUserLoginDto dto) {
//        调用微信接口，获取openId
        String openId = wechatService.getOpenId(dto.getCode());
        log.info("openId={}",openId);
//        根据openId查询中州的用户数据，查询member表
        Member member = memberService.findByOpenId(openId);
//        如果没有数据，创建Member对象，设置openId
        if (member==null){
            member = new Member();
            member.setOpenId(openId);
        }
//        调用微信接口，获取手机号
        String phoneNum = wechatService.getPhoneNum(dto.getPhoneCode());
        log.info("phoneNum={}",phoneNum);
//        把手机号设置到用户对象中，新增，修改用户信息
        if (member.getId() == null){
//            新增
            member.setPhone(phoneNum);
            member.setName(phoneNum.substring(phoneNum.length()-4));
            memberService.insert(member);
        } else {
//            如果手机号不一致就修改手机号
            if (member.getPhone().equals(phoneNum)){
                member.setPhone(phoneNum);
                memberService.update(member);
            }
        }
//        生成Token，把用户id和昵称放入token，返回给小程序
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID,member.getId());
        claims.put(Constants.JWT_USERNAME,member.getName());
        String token = JwtUtil.createJWT(jwtProp.getBase64EncodedSecretKey(), jwtProp.getTtl(), claims);
//        把token放入loginVo，返回给小程序
        LoginVo vo = new LoginVo();
        vo.setToken(token);
        vo.setNickName(member.getName());
        return vo;
    }
}
